package com.bwt.top.bwt_ad_flutter.manager;

import android.app.Activity;
import android.content.Context;

import androidx.annotation.NonNull;

import com.bwt.top.bwt_ad_flutter.AdErrorUtil;
import com.bwt.top.bwt_ad_flutter.ad.BwtBannerAd;
import com.bwt.top.bwt_ad_flutter.ad.BwtServiceAd;

import com.bwt.top.bwt_ad_flutter.config.BwtAdEventConfig;
import com.bwt.top.bwt_ad_flutter.listener.OnAdReleaseListener;
import com.bwt.top.bwt_ad_flutter.model.AdParams;
import com.bwt.top.bwt_ad_flutter.util.LogUtil;
import com.bwt.top.bwt_ad_flutter.view.factory.BwtBannerAdFactory;
import com.bwt.top.bwt_ad_flutter.view.factory.BwtServiceAdFactory;
import com.bwt.top.exception.AdError;

import java.util.HashMap;
import java.util.Map;

public class BwtServiceAdManager implements OnAdReleaseListener {

    private static BwtServiceAdManager instance;

    private final Map<String, BwtServiceAd> bwtServiceAdMap = new HashMap<>();

    public static BwtServiceAdManager getInstance(){
        if (instance == null){
            synchronized (BwtServiceAdManager.class){
                if (instance == null){
                    instance = new BwtServiceAdManager();
                }
            }
        }
        return instance;
    }

    public void loadServiceAd(Context context, @NonNull AdParams adParams, boolean loadThenShow){
        LogUtil.log("服务类型广告加载预备,adId: " + adParams.getAdId());
        if (!(context  instanceof Activity) || ((Activity) context).isFinishing()){
            LogUtil.log("服务类型广告加载失败,adId: "+adParams.getAdId()+"error:当前上下文不适合获取信息流自渲染广告!");
            BwtAdManager.getInstance().postAdEvent(BwtAdEventConfig.KEY_AD_EVENT_ON_AD_FAILED,adParams, AdErrorUtil.getError(new AdError(-1,"\"当前上下文不适合获取服务类型广告\"")));
            return;
        }
        BwtServiceAd ad = new BwtServiceAd((Activity) context,adParams,loadThenShow);
        bwtServiceAdMap.put(adParams.getAdId(),ad);
        ad.loadAd();

    }

    public BwtServiceAdManager(){
        BwtAdManager.getInstance().registerOnAdReleaseListener(this);
    }

    public Map<String, BwtServiceAd> getBwtServiceAdMap() {
        return bwtServiceAdMap;
    }

    @Override
    public void onAdRelease(String adId) {
        reloese(adId);
    }

    public void reloese(String adId){
        if (adId == null) return;
        try {
            BwtServiceAd bwtServiceAd = bwtServiceAdMap.get(adId);
            if (bwtServiceAd != null) {
                bwtServiceAd.release();
                bwtServiceAdMap.remove(adId);
            }
            BwtServiceAdFactory factory = BwtAdManager.getInstance().getBwtServiceAdFactory();
            if (factory != null) factory.release(adId);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}
